package org.xx.armory.swing.controllers;

import org.xx.armory.swing.components.AbstractPane;

import javax.swing.*;
import java.awt.Component;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

public class PaneUIContainerPropertyChangeAdapter<C extends AbstractPane<O>, O extends Component & RootPaneContainer>
        implements PropertyChangeListener {
    /**
     * {@inheritDoc}
     */
    @Override
    public final void propertyChange(
            PropertyChangeEvent event
    ) {
        @SuppressWarnings("unchecked") final C container = (C) event.getSource();
        final O owner = container.getOwner();
        if (owner == null || event.getPropertyName() == null) {
            return;
        }

        propertyChange(container, owner, event.getPropertyName(), event.getOldValue(), event.getNewValue());
    }

    protected void propertyChange(
            C container,
            O owner,
            String propertyName,
            Object oldValue,
            Object newValue
    ) {
        switch (propertyName) {
            case "defaultButton":
                setOwnerDefaultButton(owner, container.getDefaultButton());
                break;
            case "owner":
                setOwnerDefaultButton(owner, container.getDefaultButton());
                break;
            default:
                break;
        }
    }

    private void setOwnerDefaultButton(
            O owner,
            JButton defaultButton
    ) {
        if (owner != null) {
            owner.getRootPane().setDefaultButton(defaultButton);
        }
    }
}
